const config = require('../config');
const mongoose = require('mongoose');
// mongoose.set('debug', true)
mongoose.connect( config.URL , {
    useNewUrlParser: true,
    useUnifiedTopology: true
})
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
  console.log('------------------------------数据库已连接-------------------------------')
});

export default {
  /**
   * @description: 查询操作
   * @param {*} model
   * @param {object} conditions
   * @param {string} [field=""]
   * @param {object} options
   */
  Find(model: any, conditions: object, field: string = "", options?: object) {
    return new Promise((resolve, reject) => {

      model.find(conditions, field, options, (err, documents: any) => {
        if (err) {
          reject('查询出错' + err);
        } else {
          resolve({ data: documents });
        }
      })
    })
  },

  /**
   * @description 查询数据长度
   * @param {*} model
   * @param {object} conditions
   * @returns
   */
  FindCount(model: any, conditions: object) {
    return new Promise((resolve, reject) => {
      model.countDocuments(conditions, (err, count: number) => {
        if (err) {
          reject('查询出错' + err);
        } else {
          resolve(count);
        }
      })
    });
  },

  /**
   * @description 插入操作
   * @template T
   * @param {*} model
   * @param {T[]} data
   */
  Insert<T>(model: any, data: T[]) {
    return new Promise((resolve, reject) => {
      model.create(data, (err) => {
        if (err) {
          reject('插入数据出错'+err);
        } else {
          resolve({ retCode: 200, msg: '插入成功' });
        }
      })
    })
  },

  /**
   * @description 更新操作
   * @param {*} model model对象
   * @param {object} conditions 条件
   * @param {object} newData 更新的数据
   * @param {object} [options={}] 其他操作
   */
  Update(model: any, conditions: object, newData: object, options: object = {}) {
    return new Promise((resolve, reject) => {
      model.update(conditions, newData, options, (err, res) => {
        if (err) {
          reject('更新出错' + err);
        } else {
          res.n > 0 ? resolve({ retCode: 200, msg: '更新成功'}) : resolve({ retCode: 0, msg: '失败'});
        }
      })
    })
  },

  /**
   *
   *
   * @param {*} model
   * @param {object} conditions
   */
  DeleteOne(model:any, conditions: object) {
    return new Promise((resolve, reject) => {
      model.deleteMany(conditions, (err) => {
        if (err) {
          reject('删除出错' + err);
        } else {
          resolve({ retCode: 200, msg: '删除成功' });
        }
      })
    })
  }
}